//
//  PublishVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/7.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import BSImagePicker
import Photos

class PublishVC: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource , UIKeyboardViewControllerDelegate{

    var keyboard:UIKeyboardViewController?
    let contentView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    var chooseTemplate : XHInputItem?
    
    var companyItem : XHInputItem?
    var contactItem : XHInputItem?
    var phoneItem : XHInputItem?
//    var chuanzhenItem : XHInputItem?

    var type : XHInputItem?
    var channel : XHInputItem?
    var productName : XHInputItem?
//    var quality : XHInputItem?
//    var specific : XHInputItem?
//    var price : XHInputItem?
//    var num : XHInputItem?

    var factory : XHInputItem?
    var city : XHInputItem?
    var cangku : XHInputItem?
    
//    var des : XHInputItem?
//    var site : XHInputItem?
//    var comment : XHInputItem?
    var ad : XHInputItem?

    var kucunbiao : XHInputItem?
//    var pic1 : XHInputItem?
//    var pic2 : XHInputItem?
//    var pic3 : XHInputItem?
    
    let typePicker = UIPickerView.init(frame: CGRect.zero)
    let btn = UIButton.init(type: .roundedRect)
    let btn2 = UIButton.init(type: .roundedRect)
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Const.WTM_WHITE_SMOKE
        self.contentView.backgroundColor = self.view.backgroundColor
        self.contentView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        self.view.addSubview(self.contentView)
        self.title = "发布"
        
        chooseTemplate = XHInputItem("选择已有模板", onTap:self.onChooseTemplate)
        chooseTemplate?.vseperator.isHidden = true
        chooseTemplate?.nameLabel.frame = CGRect.init(x: 10, y: 0, width: 200, height: 46)
        self.contentView.addSubview(chooseTemplate!)
        
        companyItem = XHInputItem("公司名称", onTap:nil)
        companyItem?.valueField.text = User.get.company
        self.contentView.addSubview(companyItem!)

        contactItem = XHInputItem("联系人", onTap:nil)
        contactItem?.valueField.text = User.get.nickname
        self.contentView.addSubview(contactItem!)

        phoneItem = XHInputItem("手机", onTap:nil)
        phoneItem?.valueField.text = User.get.phone
        self.contentView.addSubview(phoneItem!)

//        chuanzhenItem = XHInputItem("传真", onTap:nil)
//        chuanzhenItem?.valueField.text = User.get.phone
//        self.contentView.addSubview(chuanzhenItem!)
        
//        type = XHInputItem("现货/采购",placeHolder:"请选择发布现货还是采购" ,onTap:self.onChooseType)
//        self.contentView.addSubview(type!)

        channel = XHInputItem("类别",placeHolder:"请选择类别" ,onTap:self.onChooseChannel)
        self.contentView.addSubview(channel!)
        
        productName = XHInputItem("品名", placeHolder:"请输入品名(也可以不填)",onTap:nil)
        self.contentView.addSubview(productName!)

//        quality = XHInputItem("材质", placeHolder:"请输入材质",onTap:nil)
//        self.contentView.addSubview(quality!)
//
//        specific = XHInputItem("规格", placeHolder:"请输入规格",onTap:nil)
//        self.contentView.addSubview(specific!)
        
        if User.get.contacts != 0 {
            ad = XHInputItem("今日报价信息",placeHolder:"输入报价信息，将会为您推荐到首页", onTap:nil)
            self.contentView.addSubview(ad!)
        }
        
//        price = XHInputItem("价格", placeHolder:"请输入价格",onTap:nil)
//        self.contentView.addSubview(price!)
//
//        num = XHInputItem("库存数量", placeHolder:"请输入数量(也可以不填)",onTap:nil)
//        self.contentView.addSubview(num!)
        
        
//        factory = XHInputItem("生产厂家", placeHolder:"请输入生产厂家", onTap:nil)
//        self.contentView.addSubview(factory!)

        city = XHInputItem("地区", placeHolder:"请选择地区", onTap:self.onChooseCity)
        self.contentView.addSubview(city!)

//        cangku = XHInputItem("货物存放仓库", placeHolder:"请输入仓库名", onTap:nil)
//        self.contentView.addSubview(cangku!)

        
//        des = XHInputItem("公司描述",placeHolder:"请输入公司描述", onTap:nil)
//        self.contentView.addSubview(des!)
//        site = XHInputItem("公司官网",placeHolder:"请输入公司官网", onTap:nil)
//        self.contentView.addSubview(site!)
//        comment = XHInputItem("备注",placeHolder:"请输入备注", onTap:nil)
//        self.contentView.addSubview(comment!)
        
        kucunbiao = XHInputItem("库存表",placeHolder:"点击上传", onTap:self.onChooseImage)
        kucunbiao?.showImage()
        self.contentView.addSubview(kucunbiao!)
//        pic1 = XHInputItem("货物图片1",placeHolder:"点击上传", onTap:self.onChooseImage)
//        pic1?.showImage()
//        self.contentView.addSubview(pic1!)
//        pic2 = XHInputItem("货物图片2",placeHolder:"点击上传", onTap:self.onChooseImage)
//        pic2?.showImage()
//        self.contentView.addSubview(pic2!)
//        pic3 = XHInputItem("货物图片3",placeHolder:"点击上传", onTap:self.onChooseImage)
//        pic3?.showImage()
//        self.contentView.addSubview(pic3!)

        let whiteView = UIView.init(frame: CGRect.init(x: 0, y: Const.SCREEN_HEIGHT - 64, width: Const.SCREEN_WIDTH, height: 64))
        whiteView.backgroundColor = UIColor.white
        
        btn.backgroundColor = Const.WTM_GREEN
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.layer.cornerRadius = 5
        btn.addTarget(self, action: #selector(PublishVC.save), for: .touchUpInside)
        whiteView.addSubview(btn)
        btn.frame = CGRect.init(x: 10, y: 10, width: (Const.SCREEN_WIDTH - 30)/2, height: 44)
        btn.setTitle("保存为模板", for: .normal)
        
        btn2.backgroundColor = Const.WTM_GREEN
        btn2.setTitleColor(UIColor.white, for: .normal)
        btn2.layer.cornerRadius = 5
        btn2.addTarget(self, action: #selector(PublishVC.submit), for: .touchUpInside)
        whiteView.addSubview(btn2)
        btn2.frame = CGRect.init(x: 20+(Const.SCREEN_WIDTH - 30)/2, y:10 , width: (Const.SCREEN_WIDTH - 30)/2, height: 44)
        btn2.setTitle("提交", for: .normal)
        self.view.addSubview(whiteView)
        
        self.addKeyboardToolbar()
    }

    func addKeyboardToolbar() -> Void {
        keyboard = UIKeyboardViewController.init(controllerDelegate: self)
        keyboard?.tabbarHeight  = 0;
//        keyboard?.boardDelegate = self;
        keyboard?.addToolbarToKeyboard()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func onChooseType(_ params:XHInputItem) -> Void {
        typePicker.backgroundColor = Const.WTM_LIGHTGRAY
        typePicker.autoresizingMask = UIView.AutoresizingMask.flexibleWidth;
        typePicker.dataSource = self;
        typePicker.delegate = self;
        typePicker.frame = CGRect.init(x:0, y:Const.SCREEN_HEIGHT - 216, width:Const.SCREEN_WIDTH, height:216);
        typePicker.showsSelectionIndicator = true
        self.view.addSubview(typePicker)
    }
    
    func onChooseTemplate(_ params:XHInputItem) ->Void{
    
        let vc = TemplatesListVC.init()
        vc.isChoosing = true
        vc.onComplete = { model in
            self.companyItem?.setText(model.company)
            self.contactItem?.setText(model.contact )
            self.phoneItem?.setText(model.tel )
            //        model.setType();
            self.channel?.setText(model.channelname )
            self.productName?.setText(model.productname )
//            self.quality?.setText(model.quality)
//            self.specific?.setText(model.specification )
//            self.price?.setText(model.price )
//            self.num?.setText(model.number )
            self.factory?.setText(model.factory )
            self.city?.setText(model.place )
            self.cangku?.setText(model.storehouse )
//            self.des?.setText(model.companymark )
//            self.site?.setText(model.companylink )
//            self.comment?.setText(model.mark)
            self.ad?.setText(model.advert)
            
            self.kucunbiao?.valueField.text = model.kucunpic
            self.kucunbiao?.thumbnail.kf.setImage(with:URL(string:model.kucunpic))
//            self.pic1?.valueField.text = model.productpic
//            self.pic1?.thumbnail.kf.setImage(with:URL(string:model.productpic))
//            self.pic2?.valueField.text = model.productpic1
//            self.pic2?.thumbnail.kf.setImage(with:URL(string:model.productpic1))
//            self.pic3?.valueField.text = model.productpic2
//            self.pic3?.thumbnail.kf.setImage(with:URL(string:model.productpic2))
        }
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func onChooseCity(_ params:XHInputItem) {
        let vc = CityVC.init()
        vc.singleSelect = true
        vc.onComplete = { cities in
            params.valueLabel.text = cities
        }
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func onChooseImage(_ params:XHInputItem) -> Void {
        let vc = ImagePickerController()
        vc.settings.list.cellsPerRow = { a, b in
            return 4
        }
        vc.settings.selection.max = 1
//        vc.settings.takePhotos = true
        
        presentImagePicker(vc, animated: true, select: {(asset) in
            DispatchQueue.main.async {
                vc.dismiss(animated: true, completion: {
                    let image = self.getUIImage(asset: asset)
                    self.pickImage(image , onView:params)
                    
                })
            }
        }, deselect: nil, cancel: nil, finish: nil)

    }
    
    func getUIImage(asset: PHAsset) -> UIImage? {

           var img: UIImage?
           let manager = PHImageManager.default()
           let options = PHImageRequestOptions()
           options.version = .original
           options.isSynchronous = true
           manager.requestImageData(for: asset, options: options) { data, _, _, _ in

               if let data = data {
                   img = UIImage(data: data)
               }
           }
           return img
       }
    
    func pickImage(_ image:UIImage?, onView:XHInputItem) {
        
        
        btn.backgroundColor = Const.WTM_GRAY
        btn2.backgroundColor = Const.WTM_GRAY
        btn.isEnabled = false
        btn2.isEnabled = false
        
        _ = NetworkManager.Upload(NetworkManager.UPLOAD_IMG2, image: image, ownerVC: self, callback: { (isSucess, resp) in
            self.btn.backgroundColor = Const.WTM_GREEN
            self.btn2.backgroundColor = Const.WTM_GREEN
            self.btn.isEnabled = true
            self.btn2.isEnabled = true
            if isSucess {
                let imgURL : String = resp.wtmDic["img"] as! String
                onView.thumbnail.image = image
                onView.valueField.text = imgURL
            }
        })
        
    }
    
    func onChooseChannel(_ params:XHInputItem){
        let vc = KXChannelVC.init()
        vc.singleSelect = true
        vc.title = "选择类别"
        vc.onComplete = { cities in
            params.valueLabel.text = cities
        }
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func collectInfo() ->[String:Any]? {
        let requiredList = [companyItem,contactItem,phoneItem,factory,cangku,city,channel]
        
        for item in requiredList {
            if item?.getText()?.count == 0 {
                self.navigationController?.view.makeToast((item?.hint)!)
                return nil
            }
        }
        let model = XianhuoModel.init()
        
        model.company = (companyItem?.getText())!
        model.contact = (contactItem?.getText())!
        model.tel = (phoneItem?.getText())!
        //        model.setType();
        model.channelname = (channel?.getText())!
        model.productname = (productName?.getText())!
//        model.quality = (quality?.getText())!
//        model.specification = (specific?.getText())!
//        model.price = (price?.getText())!
//        model.number = (num?.getText())!
//        model.factory = (factory?.getText())!
        model.place = (city?.getText())!
//        model.storehouse = (cangku?.getText())!
//        model.companymark = (des?.getText())!
//        model.companylink = (site?.getText())!
//        model.mark = (comment?.getText())!
        model.userid = User.get.userId
        
        let now = Date.init()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let advert = formatter.string(from: now) + "发布：" + (ad?.getText())!

        model.advert = advert
        
        model.kucunpic = (kucunbiao?.getText())!
//        model.productpic = (pic1?.getText())!
//        model.productpic1 = (pic2?.getText())!
//        model.productpic2 = (pic3?.getText())!
        
        return model.serialize()
    }
    
    @objc func submit() -> Void {
        
        guard let params = self.collectInfo() else{
            return
        }
        self.save(true)
        
        _ = NetworkManager.POST(NetworkManager.XIANHUO_POST, params: params, ownerVC: self, callback: { (isSuccess, resp) in
            if(isSuccess){
                let alert = UIAlertController.init(title: "提示", message: "发布成功，请您耐心等待审核结果，可以在\"我的发布\"页面查看审核进度", preferredStyle: .alert)
                alert.addAction(UIAlertAction.init(title: "我知道了", style: .default, handler:  {_ in
                    self.navigationController?.popViewController()
                }))
                DispatchQueue.main.async {
                    self.navigationController?.present(alert, animated: true, completion: nil)
                }
                
            }
        })
    }
    
    @objc func save(_ hideAlert: Bool = false) -> Void {
        guard let params = self.collectInfo() else{
            return
        }
        _ = NetworkManager.POST(NetworkManager.XIANHUO_TEMPLATE_ADD, params: params, ownerVC: self, callback: { (isSuccess, resp) in
            if (!hideAlert){
                let alert = UIAlertController.init(title: "提示", message: "成功保存为模板！", preferredStyle: .alert)
                alert.addAction(UIAlertAction.init(title: "我知道了", style: .default, handler:nil))
                
                DispatchQueue.main.async {
                    self.navigationController?.present(alert, animated: true, completion: nil)
                }
            }
        })
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        var y:CGFloat = 10
        var i = 0
        for iView in contentView.subviews {
            if iView.isKind(of: XHInputItem.self) {
                let item : XHInputItem = iView as! XHInputItem
                item.setY(y)
                y += 46.0 - Const.ONE_PIXEL //压住线
                i += 1
                if ( i == 1 || i == 4 || i == 11 || i == 14 || i == 18) {
                    y += 10.0
                }
            }
        }
        
        self.contentView.contentSize = CGSize.init(width: Const.SCREEN_WIDTH, height: y + 46)
    }
    
    //MARK:-UIPickerView
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return 2
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if row == 0 {
            return "现货"
        }else {
            return "采购"
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.type?.valueLabel.text = row == 0 ? "现货" : "采购"
        pickerView.removeFromSuperview()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
}
